package main

import (
	"context"
	"flag"
	"fmt"
	"gitee.com/windcoder/geekbangCloudNativeWork/go/httpserver/httpServer"
	"gitee.com/windcoder/geekbangCloudNativeWork/go/httpserver/metrics"
	"github.com/golang/glog"
	"net/http"
	"os"
	"os/signal"
	"strconv"
	"syscall"
	"time"
)

func init() {

}

func main() {
	// 获取 glog 日志配置
	flag.Set("v", os.Getenv("GLOG_V"))
	flag.Set("stderrthreshold", os.Getenv("GLOG_STDERRLEVEL"))
	flag.Set("log_dir", os.Getenv("GLOG_DIR"))
	metrics.Register()
	// 防止 ERROR: logging before flag.Parse
	flag.Parse()
	defer glog.Flush()
	// --alsologtostderr=true
	glog.V(2).Infoln("The HttpServer 8080 is Starting...")
	// 获取 httpServer 绑定地址配置
	server := httpServer.NewServe(os.Getenv("WHTTP_URL"), os.Getenv("WHTTP_PORT"))

	// 创建系统信号接收器，监听终止信号
	stopChan := make(chan os.Signal)
	// os.Interrupt,syscall.SIGINT ctrl+c
	signal.Notify(stopChan, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
	go func() {
		// 启动 HTTP 服务
		err := server.ListenAndServe()
		if err != nil {
			if err == http.ErrServerClosed {
				glog.Warning("Server closed under request")
			} else {
				glog.Fatalln(fmt.Sprintf("Server  unexpected，Could not gracefully use the server: %v \n", err))
			}
		}

	}()
	graceTimeOut, err := strconv.Atoi(os.Getenv("GRACEFUL_TIMEOUT"))
	if err != nil {
		graceTimeOut = 30
		glog.Warning("GRACEFUL_TIMEOUT type conversion failed")
	}
	// 关停 HTTP 服务
	osCall := <-stopChan
	glog.V(3).Infoln(fmt.Sprintf("system call: %+v", osCall))
	// https://github.com/tylerchr/examples/tree/master/draining
	timeOut := time.Duration(graceTimeOut) * time.Second
	ctx, cancle := context.WithTimeout(context.Background(), timeOut)
	defer cancle()
	if err := server.Shutdown(ctx); err != nil {
		glog.Fatalln(fmt.Sprintf("Could not gracefully shutdown the server: %v  \n", err))
	}

}
